﻿using QWManage.DAL;
using QWManage.Model;
using QWManage.Utils;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows.Forms;

namespace QWManage.Forms
{

    public partial class FrmData : Form
    {
        private Thread _thread;
        public FrmData()
        {
            InitializeComponent();
        }

        private void FrmData_Load(object sender, EventArgs e)
        {
            this.txtResults.Text = "数据统计分析中，请稍等...";
            this.txtResults.Enabled = false;
            this.btnCopy.Enabled = false;
            this.FormClosing += FrmData_FormClosing;
            _thread = new Thread(new ThreadStart(workService));
            _thread.Start();
        }

        private void FrmData_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_thread != null && _thread.IsAlive) _thread.Abort();
        }

        private void workService()
        {
            try
            {
                List<string> lines = new List<string>();
                UserDAL userDAL = new UserDAL();

                HashSet<string> userIds = new HashSet<string>();
                List<UserInfo> users = userDAL.GetUserInfos();

                CustomerDAL customerDAL = new CustomerDAL();
                List<CustomerInfo> customers = customerDAL.GetCustomerInfos();

                CustomersGroupsDAL customerGroupDAL = new CustomersGroupsDAL();
                List<CustomerGroupInfo> customersGroups = customerGroupDAL.GetCustomerGroupInfos();

                HashSet<string> customerIds = new HashSet<string>();
                HashSet<string> allMembers = new HashSet<string>();
                //allMembers 包括 用户，用户下的客户，以及群里面的成员
                foreach (UserInfo user in users)
                {
                    customerIds.Add(user.UserID);
                    userIds.Add(user.UserID);
                    allMembers.Add(user.UserID);
                }
                foreach (CustomerInfo customer in customers)
                {
                    customerIds.Add(customer.Exuserid);
                    allMembers.Add(customer.Exuserid);
                }
                foreach (CustomerGroupInfo customerGroupInfo in customersGroups)
                {
                    allMembers.Add(customerGroupInfo.UserID);
                }

                lines.Add($"一共有 {Common.FormatInt32(allMembers.Count)} 人");
                lines.Add($"用户有 {Common.FormatInt32(users.Count)} 人");
                lines.Add($"客户有 {Common.FormatInt32(customerIds.Count - users.Count)} 人");

                GroupDAL groupDAL = new GroupDAL();
                List<GroupInfo> groups = groupDAL.GetGroupInfos();
                lines.Add($"一共有 {Common.FormatInt32(groups.Count)} 个群");
                CustomersGroupsDAL customersGroupsDAL = new CustomersGroupsDAL();
                List<CustomerGroupInfo> customerGroups = customersGroupsDAL.GetCustomerGroupInfos();

                Dictionary<string, List<string>> dic = new Dictionary<string, List<string>>();

                foreach (CustomerGroupInfo customerGroupInfo in customerGroups)
                {
                    //用户的不要
                    if (userIds.Contains(customerGroupInfo.UserID)) continue;
                    //不在群的不要
                    if (!customerGroupInfo.Status) continue;
                    string key = customerGroupInfo.UserID;
                    if (!dic.ContainsKey(key))
                    {
                        dic.Add(key, new List<string>());
                    }
                    if (!dic[key].Contains(customerGroupInfo.GroupID))
                        dic[key].Add(customerGroupInfo.GroupID);
                }
                lines.Add($"有 {Common.FormatInt32(dic.Keys.Count)} 人在群，占比 {calculatePersent(dic.Keys.Count, customers.Count)}");
                lines.Add($"有 {Common.FormatInt32(customerIds.Count - dic.Keys.Count)} 人不在群，占比 {calculatePersent(customerIds.Count - dic.Keys.Count, customers.Count)}");
                int total = 0;
                foreach (string key in dic.Keys)
                {
                    if (dic[key].Count > 3)
                        total++;
                }
                lines.Add($"有 {Common.FormatInt32(total)} 人重复进群，占比 {calculatePersent(total, customers.Count)}");
                List<string> list = new List<string>();
                foreach (string line in lines)
                {
                    list.Add(line);
                    list.Add("");
                }
                if (this.InvokeRequired)
                {
                    this.Invoke(new MethodInvoker(delegate
                    {
                        txtResults.Lines = list.ToArray();
                    }));
                }
            }
            catch (ThreadAbortException) { }
            catch (Exception ex)
            {
                Logs.LogMgr.Log(ex);
                Common.MessageBoxWarning(ex.Message);
            }
            finally
            {
                try
                {
                    if (this.InvokeRequired)
                    {
                        this.Invoke(new MethodInvoker(delegate
                        {
                            txtResults.Enabled = true;
                            btnCopy.Enabled = true;
                        }));
                    }
                }
                catch { }
            }
        }

        private static string calculatePersent(double num, double total)
        {
            double percentage = (num / total) * 100;
            // 保留两位小数
            percentage = Math.Round(percentage, 2);
            return percentage.ToString() + "%";
        }

        private void btnCopy_Click(object sender, EventArgs e)
        {
            if (txtResults.Text.Trim().Length == 0)
            {
                Common.MessageBoxWarning("数据为空，无法复制");
                return;
            }
            txtResults.SelectAll();
            txtResults.Focus();
            Clipboard.SetText(txtResults.Text.Trim());
        }
    }
}
